package com.alipay.rebate.shop.service.customer.impl;

import com.alipay.rebate.shop.constants.LogOffApplyConstant;
import com.alipay.rebate.shop.constants.StatusCode;
import com.alipay.rebate.shop.core.AbstractService;
import com.alipay.rebate.shop.dao.mapper.LogOffApplyMapper;
import com.alipay.rebate.shop.dao.mapper.UserMapper;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.model.LogOffApply;
import com.alipay.rebate.shop.model.User;
import com.alipay.rebate.shop.service.customer.CustomerLogOffApplyService;
import java.util.Date;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * Created by CodeGenerator on 2020/01/19.
 */
@Service
@Transactional
public class CustomerLogOffApplyServiceImpl extends AbstractService<LogOffApply> implements
    CustomerLogOffApplyService {
    @Resource
    private LogOffApplyMapper logOffApplyMapper;
    @Resource
    private UserMapper userMapper;

    @Override
    public int add(Long userId) {
        LogOffApply dbRecord = logOffApplyMapper.selectLatestByUserId(userId);
        if(dbRecord != null && LogOffApplyConstant.ONGOING.equals(dbRecord.getStatus())){
            throw new BusinessException("您已提交注销申请",StatusCode.INTERNAL_ERROR);
        }
        if(dbRecord != null && LogOffApplyConstant.SUCCESS.equals(dbRecord.getStatus())){
            throw new BusinessException("账号已注销",StatusCode.INTERNAL_ERROR);
        }
        User user = userMapper.selectById(userId);
        LogOffApply logOffApply = new LogOffApply();
        logOffApply.setUserId(userId);
        logOffApply.setUserName(user.getUserNickName());
        logOffApply.setPhone(user.getPhone());
        Date date = new Date();
        logOffApply.setCreateTime(date);
        logOffApply.setUpdateTime(date);
        logOffApply.setStatus(LogOffApplyConstant.ONGOING);
        return logOffApplyMapper.insertSelective(logOffApply);
    }

    @Override
    public LogOffApply latestApply(Long userId) {
        return logOffApplyMapper.selectLatestByUserId(userId);
    }
}
